package com.stx.dao.impl;

import com.stx.dao.AccountDao;
import com.stx.pojo.Account;
import com.stx.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class AccountImpl implements AccountDao {
    private JdbcTemplate template =new JdbcTemplate(JDBCUtils.getDataSource());


    @Override
    public int addAccount(Account account) {
        String sql = "insert into account values(?,?,?)";
        int result = template.update(sql, account.getId(), account.getUsername(), account.getBalance());
        return result;
    }

    @Override
    public int deleteAccount(int id) {
        String sql = "delete from account where id = ?";
        int result = template.update(sql, id);
        return result;
    }

    @Override
    public Account findAccountById(int id) {
        String sql = "select * from account where id = ? ";
        List<Account> accountList = template.query(sql, new BeanPropertyRowMapper<>(Account.class), id);
        // queryforobject 不知道为什么在这里会报错就先这样吧
        return accountList.get(0);
    }

    @Override
    public List<Account> findAllAccount() {
        String sql = "select * from account";
        List<Account> accountList = template.query(sql, new BeanPropertyRowMapper<>(Account.class));
        return accountList;
    }

    @Override
    public int updateAccount(Account account) {
        String sql = "update account set username = ? , balance = ? where id = ? ";
        int result = template.update(sql, account.getUsername(), account.getBalance(), account.getId());
        return result;
    }
}
